<?php
/**  
 * @file TokenManager.php  
 * @author 辰然 <3469807212@qq.com>  
 * @created 2024年11月30日  
 * @signature "创意无限"  
 * @copyright Copyright (c) 2024 辰然. All rights reserved. 本软件版权归辰然所有，未经许可，不得开源或用于商业用途。  
 *  
 * 描述: Token类
 */  
class TokenManager {
    private $sessionKey = 'tokens';
    private $tokenLength = 6;
    private $expireDays = 3;
    private $storageFile;
    private $tokens = [];
    
    public function __construct() {
        $this->storageFile = __DIR__ . '/storage/tokens.json';
        $this->loadTokens();
    }
    
    private function loadTokens() {
        if (file_exists($this->storageFile)) {
            $content = file_get_contents($this->storageFile);
            $this->tokens = json_decode($content, true) ?: [];
        }
    }
    
    private function saveTokens() {
        $directory = dirname($this->storageFile);
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true);
        }
        file_put_contents($this->storageFile, json_encode($this->tokens));
    }
    
    public function generateToken($userInfo) {
        $token = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        
        $this->tokens[$token] = [
            'create_time' => time(),
            'expire_time' => strtotime("+{$this->expireDays} days"),
            'user_info' => $userInfo
        ];
        
        $this->saveTokens();
        
        return [
            'token' => $token,
            'expire_time' => $this->tokens[$token]['expire_time']
        ];
    }
    
    public function validateToken($token) {
        if (!isset($this->tokens[$token])) {
            return [
                'valid' => false,
                'message' => 'Token 不存在'
            ];
        }
        
        $tokenInfo = $this->tokens[$token];
        $now = time();
        
        if ($now > $tokenInfo['expire_time']) {
            $this->deleteToken($token);
            return [
                'valid' => false,
                'message' => 'Token 已过期'
            ];
        }
        
        return [
            'valid' => true,
            'message' => 'Token 有效',
            'days_left' => ceil(($tokenInfo['expire_time'] - $now) / 86400),
            'user_info' => $tokenInfo['user_info']
        ];
    }
    
    public function refreshToken($token) {
        if (!isset($this->tokens[$token])) {
            return [
                'success' => false,
                'message' => 'Token 不存在'
            ];
        }
        
        $tokenInfo = $this->tokens[$token];
        $tokenInfo['expire_time'] = strtotime("+{$this->expireDays} days");
        $this->tokens[$token] = $tokenInfo;
        
        $this->saveTokens();
        
        return [
            'success' => true,
            'message' => 'Token 已刷新',
            'expire_time' => $tokenInfo['expire_time']
        ];
    }
    
    public function deleteToken($token) {
        if (isset($this->tokens[$token])) {
            unset($this->tokens[$token]);
            $this->saveTokens();
            return true;
        }
        return false;
    }
    
    public function cleanExpiredTokens() {
        $now = time();
        $count = 0;
        
        foreach ($this->tokens as $token => $info) {
            if ($now > $info['expire_time']) {
                unset($this->tokens[$token]);
                $count++;
            }
        }
        
        $this->saveTokens();
        
        return $count;
    }
    
    public function hasUserGeneratedTokenToday($openid) {
        $today = strtotime('today');
        
        foreach ($this->tokens as $tokenInfo) {
            if ($tokenInfo['user_info']['openid'] === $openid && 
                $tokenInfo['create_time'] >= $today) {
                return true;
            }
        }
        return false;
    }
}
?>
